<template>

  <el-row :gutter="20">

    <el-col :span="18">
      <el-card class="mainContainer dataShow" shadow="never">
        <el-row>
          <el-col :span="8">
            <el-text>生成数据条数:</el-text>
            <el-input-number v-model="dataNum"
                             :min="1"
                             :max="100"
                             :precision="0" :step="1"/>
          </el-col>
          <el-col :span="3">
            <el-button :loading="getDataLoading"
                       type="primary" @click="getData">
              数据生成
            </el-button>
          </el-col>
          <el-col :span="10"></el-col>
          <el-col :span="3" style="display: flex;justify-content: flex-end">
            <el-button type="primary" @click="copyAllData">复制全部</el-button>
          </el-col>
        </el-row>

        <el-scrollbar height="calc(100vh - 220px)">
          <el-row v-for="item in resultData">
            <el-col :span="21">
              <el-input type="textarea" v-model="item.data"></el-input>
            </el-col>
            <el-col :span="3" style="display: flex;justify-content: flex-end">
              <el-button type="primary" @click="copyData(item.data)">复制单条</el-button>
            </el-col>
          </el-row>
        </el-scrollbar>


      </el-card>
    </el-col>


    <el-col :span="6">
      <el-card class="mainContainer dataArgs" shadow="never">
        <el-row>
          <el-col :span="12">
            <el-button type="primary"
                       @click="openCatDataArgsDialog">
              数据类型
            </el-button>
          </el-col>
          <el-col :span="12">
            <span>已选择: </span>
            <el-text size="large" type="primary">{{ dataArgs.name }}</el-text>

          </el-col>
        </el-row>

        <el-form label-width="100" labelPosition="top"
                 :model="dataGenerationArgs.args"
                 :rules="argsRules">
          <el-scrollbar height="calc(100vh - 220px)">
            <el-row>
              <el-col :span="24">
                <el-form-item label="语言: ">
                  <el-select v-model="dataGenerationArgs.language" filterable style="width: 100%">
                    <el-option
                        v-for="item in languageOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-for="item in fieldArgs">

                <el-form-item :label="item.name+':'" :prop="item.field">
                  <template #label>
                    {{ item.name }}
                    <el-popover v-if="item.description" effect="light" trigger="hover" placement="top" width="auto">
                      <template #default>
                        <el-scrollbar max-height="300px">
                          <el-text style="white-space:pre-wrap;">{{ item.description }}</el-text>
                        </el-scrollbar>
                      </template>
                      <template #reference>
                        <el-icon>
                          <QuestionFilled/>
                        </el-icon>
                      </template>
                    </el-popover>
                  </template>

                  <!--                  number-->
                  <el-input v-if="item.type==='number'"
                            v-model.number="dataGenerationArgs.args[item.field]">
                  </el-input>

                  <!--                  customSelectString-->
                  <el-select v-if="item.type==='customSelectString'"
                             style="width: 100%;"
                             v-model="dataGenerationArgs.args[item.field]"
                             clearable
                             multiple
                             filterable
                             allow-create
                             default-first-option
                             :reserve-keyword="false"
                             :placeholder="'请输入'+ item.name +'的选项'"
                  >
                    <el-option
                        v-for="item in customSelectStringOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>


                </el-form-item>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-form>
      </el-card>

    </el-col>

  </el-row>


  <!--  选择数据类型-->
  <el-dialog
      v-model="centerDialogVisible"
      title="选择数据类型"
      width="80%"
      align-center
      :before-close="cancelSelect"
  >
    <el-row :gutter="10">
      <el-col :span="6">
        <el-input clearable @input="searchDataArgs"
                  v-model="catKeywords"
                  placeholder="输入数据分类"></el-input>
      </el-col>
      <el-col :span="6">
        <el-input clearable @input="searchDataArgs"
                  v-model="dataKeywords"
                  placeholder="输入数据类型"></el-input>
      </el-col>
    </el-row>

    <el-scrollbar height="calc(100vh - 300px)">
      <div class="catDataArgContainer" v-for="item in catDataArgs">
        <div style="margin-top: 20px;margin-bottom: 10px">
          <el-text style="font-size: 20px;">{{ item.name }}</el-text>
        </div>
        <el-row :gutter="10" style="margin: 0">
          <el-col :span="4" v-for="argsItem in item.dataArgs">
            <div class="data_card"
                 @click="changeSelectedDataArgsId(argsItem.id)"
                 :class="{data_card_light:argsItem.id === selectedDataArgsId}">
              <el-text truncated>{{ argsItem.name }}</el-text>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-scrollbar>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSelect">取消</el-button>
        <el-button type="primary" @click="changeDataArgsId">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>

import {ref, onMounted, computed, reactive} from 'vue'
import {getCatDataArgs, Data, getFirstDataArgId} from '@/apis/dataGeneration/index.js'
import {
  getDataArgsById,
} from "@/apis/dataGeneration/dataGenerationConfig.js";

import languageOptions from '@/util/languageData.js'

// 当前数据类型的数据
let dataArgs = ref({})
// 当前数据类型配置的JSON参数
let fieldArgs = ref({})
// 一页多多少条数据
const dataNum = ref(1)
// {field: "text", args: {size: 12}}
// 点击生成数据时，提交的请求body
const dataGenerationArgs = ref({language: "zh-CN", field: null, dataNumber: dataNum, args: {}})
// 自定义字符串选项
const customSelectStringOptions = ref({})


const argsRules = reactive({})

let numberCheck = reactive({})
const checkNumber = (rule, value, callback) => {
  if (!value) {
    callback(new Error(numberCheck.name + "必须填写！"))
  }
  if (value < numberCheck.min_number) {
    callback(new Error("不能小于最小数:" + numberCheck.min_number))
  }
  if (value > numberCheck.max_number) {
    callback(new Error("不能大于最大数:" + numberCheck.max_number))
  }
}

const setDataGenerationFormArgs = () => {
  fieldArgs.value.forEach(item => {
    // 数字类型
    if (item.type === 'number') {
      numberCheck = item
      argsRules[item.field] = [{validator: checkNumber, trigger: 'blur'}]
      dataGenerationArgs.value.args[item.field] = parseInt(item.min_number)
    } else {
      dataGenerationArgs.value.args[item.field] = null
    }
    console.log(dataGenerationArgs.value)

  })
}

// 获取数据类型字段信息
const getDataArgs = (id) => {
  getDataArgsById(id).then(res => {
    dataArgs.value = res
    //   重置请求参数
    dataGenerationArgs.value.args = {}
    dataGenerationArgs.value.field = res.value
    fieldArgs.value = JSON.parse(dataArgs.value.args)
    setDataGenerationFormArgs()

  })
}


// 在页面已经选择(初始化进来，m默认给第一个ID）
const dataArgsId = ref('')
onMounted(async () => {
  getFirstDataArgId().then(res => {
    dataArgsId.value = res.data
    getDataArgs(dataArgsId.value)
  }).catch(error => {
    ElMessage({
      message: '无数据类型数据！请先添加或启用！',
      type: 'error',
    });
  });


})

// 在模态框中选中
const selectedDataArgsId = ref('')
const changeSelectedDataArgsId = (id) => {
  selectedDataArgsId.value = id;
  console.log(selectedDataArgsId.value)
}


const centerDialogVisible = ref(false)

const catDataArgs = ref([])

// 打开选择数据类型框
const openCatDataArgsDialog = async () => {
  centerDialogVisible.value = true;
  selectedDataArgsId.value = dataArgsId.value;
  getCatDataArgs({catName: '', dataName: ''}).then(res => {
    catDataArgs.value = res.data;
  })
}

// 改变搜索词，搜索数据类型
const catKeywords = ref('')
const dataKeywords = ref('')
const searchDataArgs = async () => {
  getCatDataArgs({catName: catKeywords.value, dataName: dataKeywords.value}).then(res => {
    catDataArgs.value = res.data;
  })
}

// 取消选择
const cancelSelect = () => {
  catKeywords.value = ''
  dataKeywords.value = ''
  centerDialogVisible.value = false;
}

// 确定选择
const changeDataArgsId = () => {
  centerDialogVisible.value = false;
  dataArgsId.value = selectedDataArgsId.value;
  getDataArgs(dataArgsId.value)
}


let resultData = ref([{"data": ""}])
let getDataLoading = ref(false)

const getData = async () => {
  getDataLoading.value = true;
  Data(dataGenerationArgs.value).then(res => {
    resultData.value = res.data;
    getDataLoading.value = false;
  }).catch(e => {
    getDataLoading.value = false;
  })
}


//    复制
import {useClipboard} from '@vueuse/core'
import {ElMessage} from "element-plus";

const source = ref('')
const {text, copy, copied, isSupported} = useClipboard({source})

const copyData = (data) => {
  if (isSupported.value) {
    copy(data).then(res => {
      ElMessage({
        message: '已复制',
        type: 'success',
      });
    })
  } else {
    ElMessage({
      message: '浏览器不支持复制',
      type: 'danger',
    });
  }
}

const copyAllData = () => {
  let allDataString = ''
  resultData.value.forEach(item => {
    allDataString += item.data + '\n'
  })
  copyData(allDataString);
}


</script>

<style lang="scss" scoped>

.dataArgs .el-row {
  margin-bottom: 20px;
}

.dataShow .el-row {
  margin-bottom: 20px;
}


.data_card {
  background-color: var(--el-color-info-light-7);
  border-radius: var(--el-border-radius-base);
  height: 50px;
  border-color: var(--el-color-primary-light-9);
  padding: 5px;
  display: flex;
  align-items: center;
  justify-content: center;

  margin: 5px 0;


  &:hover {
    background-color: var(--el-color-primary);
  }
}

.data_card_light {
  background-color: var(--el-color-primary);
}

</style>
